package cn.tj212.xiaoyin.portal.business.impl;

import cn.tj212.xiaoyin.core.consts.domain.ConstsClassify;
import cn.tj212.xiaoyin.core.consts.service.IConstsClassifyService;
import cn.tj212.xiaoyin.core.course.domain.Course;
import cn.tj212.xiaoyin.core.course.domain.CourseQueryDto;
import cn.tj212.xiaoyin.core.course.service.ICourseService;
import cn.tj212.xiaoyin.portal.business.IPortalBusiness;
import cn.tj212.xiaoyin.portal.vo.ConstsClassifyVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PortalBusinessImpl implements IPortalBusiness {

    @Autowired
    private IConstsClassifyService constsClassifyService;

    @Autowired
    private ICourseService courseService;

    /**
     * 获取所有分类，包括一级分类&二级分类
     * @return
     */
    @Override
    public List<ConstsClassifyVO> queryAllClassify() {
        List<ConstsClassifyVO> resultList=new ArrayList<ConstsClassifyVO>();
        for (ConstsClassifyVO vo:this.queryAllClassifyMap().values()
             ) {
            resultList.add(vo);
        }
        return resultList;
    }

    @Override
    public void prepareRecomdCourses(List<ConstsClassifyVO> classifyVOList) {
        if (CollectionUtils.isNotEmpty(classifyVOList)){
            for (ConstsClassifyVO item:classifyVOList
                 ) {
                CourseQueryDto queryEntity=new CourseQueryDto();
                queryEntity.setCount(5);
                queryEntity.setSortField("weight");
                queryEntity.setClassify(item.getCode());//分类code

                List<Course> tmpList=this.courseService.queryList(queryEntity);
                if (CollectionUtils.isNotEmpty(tmpList)){
                    item.setRecomdCourseList(tmpList);
                }
            }
        }
    }

    @Override
    public Map<String, ConstsClassifyVO> queryAllClassifyMap() {
        Map<String, ConstsClassifyVO> resultMap = new LinkedHashMap<String, ConstsClassifyVO>();
        Iterator<ConstsClassify> it = constsClassifyService.queryAll().iterator();
        while (it.hasNext()) {
            ConstsClassify c = it.next();
            if ("0".equals(c.getParentCode())) {//这是一级分类
                ConstsClassifyVO vo = new ConstsClassifyVO();
                BeanUtils.copyProperties(c,vo);
                resultMap.put(vo.getCode(),vo);
            }else {//二级分类
                if (null!=resultMap.get(c.getParentCode()))
                    resultMap.get(c.getParentCode()).getSubClassifyList().add(c);//添加到子分类中
            }
        }
        return resultMap;
    }
}
